/**
 * @param {number[]} start1
 * @param {number[]} end1
 * @param {number[]} start2
 * @param {number[]} end2
 * @return {number[]}
 */
var Vec2DDistance = function (v1, v2) {

    var ySeparation = v2.y - v1.y;
    var xSeparation = v2.x - v1.x;

    return Math.sqrt(ySeparation * ySeparation + xSeparation * xSeparation);
}
var intersection = function (start1, end1, start2, end2) {
    var A = {
        x: start1[0],
        y: start1[1]
    };
    var B = {
        x: end1[0],
        y: end1[1]
    };
    var C = {
        x: start2[0],
        y: start2[1]
    };
    var D = {
        x: end2[0],
        y: end2[1]
    };

    // if ((rBot == 0) || (sBot == 0)) {
        //lines are parallel
        // console.log(rBot, sBot);
        if((B.y - A.y) * (C.x - A.x) == (C.y - A.y) * (B.x - A.x)){//平行的判断
            var min = Math.min;
            var max = Math.max;
            if (min(C.x, D.x) > max(A.x, B.x) || min(A.x, B.x) > max(C.x, D.x)) return []; //分离
            if (min(C.y, D.y) > max(A.y, B.y) || min(A.y, B.y) > max(C.y, D.y)) return []; //分离
            list = [A, B, C, D].sort(function (a, b) {
                return a.x - b.x;
            });
            if(A.x == B.x &&  B.x==C.x && C.x==D.x){
                list = list.sort(function (a, b) {
                    return a.y - b.y;
                });
            }
            // console.log([A, B, C, D], list);
            return [list[1].x, list[1].y]; //取第二小的即所求交点
        }
        // return [];
    // }

    var rTop = (A.y - C.y) * (D.x - C.x) - (A.x - C.x) * (D.y - C.y);
    var rBot = (B.x - A.x) * (D.y - C.y) - (B.y - A.y) * (D.x - C.x);

    var sTop = (A.y - C.y) * (B.x - A.x) - (A.x - C.x) * (B.y - A.y);
    var sBot = (B.x - A.x) * (D.y - C.y) - (B.y - A.y) * (D.x - C.x);
    
    var r = rTop / rBot;
    var s = sTop / sBot;
// console.log(r, s);
    if ((r >= 0) && (r <= 1) && (s >= 0) && (s <= 1)) {
        // dist = Vec2DDistance(A,B) * r;

        var pointX = A.x + r * (B.x - A.x);
        var pointY = A.y + r * (B.y - A.y);
        return [pointX, pointY];
    } else {
        // dist = 0;

        return [];
    }

};

// console.log(intersection([0, 0], [1, 0], [1, 1], [0, -1]));
console.log(intersection([0, 3], [0, 6], [0, 1], [0, 5]));
console.log(intersection([0,0],[1,1],[1,0],[2,1]));
console.log(intersection([0,0],[1,-1],[0,0],[-1,1]));
console.log(intersection([1,0],[1,1],[-1,0],[3,2]));

